const query = require('../utils/query')
// 主页
const Home = (req, res) => {
  res.send('奈何?取之尽锱铢,用之如泥沙')
}
// 根据id获取
const getById = async(id) => {
  const sql = `select * from user WHERE id=${id}`
  const result = await query(sql)
  return result[0]
}
// 查询列表
const GetUsers = async(req, res) => {
  const sql = 'select * from user'
  const result = await query(sql)
  res.json({ collection: result })
}
// 查询单个
const GetUser = async(req, res) => {
  const id = parseInt(req.params.id)
  if (!id) {
    res.status(400)
    return res.json({ error: 'Id must be have' })
  }
  const result = await getById(id)
  if (!result) {
    res.status(404)
    res.json({ error: `User ${id} not found` })
    return
  }
  res.json({ document: result })
}
// 新增
const CreateUser = async(req, res) => {
  if (!req.body) {
    res.status(400)
    res.json({ error: 'Request body cannot be empty' })
    return
  }
  const { nickName, gender } = req.body
  if (!nickName || !gender) {
    res.status(400)
    res.json({ error: 'Invalid payload is provided' })
    return
  }
  const sql = `INSERT INTO user (nickname, gender) VALUES ('${nickName}', ${parseInt(gender)})`
  const { insertId } = await query(sql)
  const result = await getById(insertId || 0)
  res.status(201)
  res.json({ document: result })
}
// 修改
const UpdateUser = async(req, res) => {
  const id = parseInt(req.params.id)
  if (!id || !req.body) {
    res.status(400)
    res.json({ error: 'Invalid request' })
    return
  }
  const { nickName, gender } = req.body
  if (!nickName || !gender) {
    res.status(400)
    res.json({ error: 'Invalid payload is provided' })
    return
  }
  const sql = `UPDATE user SET nickName='${nickName}', gender=${parseInt(gender)} WHERE id=${id}`
  await query(sql)
  const result = await getById(id)
  res.status(200)
  res.json({ document: result })
}
// 删除
const DeleteUser = async(req, res) => {
  const id = parseInt(req.params.id)
  if (!id) {
    res.status(400)
    res.json({ error: 'Id must be have' })
    return
  }
  const sql = `DELETE FROM user WHERE id=${id}`
  await query(sql)
  res.status = 204
  res.end()
}
module.exports = {
  Home,
  GetUsers,
  GetUser,
  CreateUser,
  UpdateUser,
  DeleteUser
}